package com.chen.recruit.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.chen.recruit.common.annotation.Log;
import com.chen.recruit.common.api.CommonResult;
import com.chen.recruit.common.constants.SysConstants;
import com.chen.recruit.common.enums.BusinessType;
import com.chen.recruit.common.utils.ExcelUtils;
import com.chen.recruit.common.utils.SysUtils;
import com.chen.recruit.common.valid.AddGroup;
import com.chen.recruit.common.valid.UpdateGroup;
import com.chen.recruit.domain.*;
import com.chen.recruit.domain.dto.UserDto;
import com.chen.recruit.domain.model.PageQuery;
import com.chen.recruit.domain.vo.*;
import com.chen.recruit.service.*;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

import static com.chen.recruit.common.enums.UserType.*;

@Api(tags = "用户管理 UserController")
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user")
public class UserController {

    private final UserService userService;
    private final RoleService roleService;
    private final MenuService menuService;
    private final PostService postService;
    private final CollegeService collegeService;

    @ApiOperation("新增管理员")
    @SaCheckPermission("system:admin:add")
    @Log(module = "系统管理-用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/admin")
    public CommonResult addAdmin(@Validated(AddGroup.class) @RequestBody Admin admin) {
        return userService.addOrUpdateUser(BeanUtil.toBean(admin, User.class), ADMIN);
    }

    @ApiOperation("删除管理员")
    @SaCheckPermission("system:admin:delete")
    @Log(module = "系统管理-用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/admin/{ids}")
    public CommonResult deleteAdmin(@PathVariable Integer[] ids) {
        return userService.deleteUserByIds(ids);
    }

    @ApiOperation("更新管理员")
    @SaCheckPermission("system:admin:update")
    @Log(module = "系统管理-用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/admin")
    public CommonResult updateAdmin(@Validated(UpdateGroup.class) @RequestBody Admin admin) {
        return userService.addOrUpdateUser(BeanUtil.toBean(admin, User.class), ADMIN);
    }

    @ApiOperation("查询管理员详情")
    @SaCheckPermission("system:admin:update")
    @GetMapping("/admin/{id}")
    public CommonResult getAdmin(@PathVariable Integer id) {
        return CommonResult.success(userService.getUserInfoById(id, ADMIN));
    }

    @ApiOperation("查询用户列表")
    @SaCheckPermission("system:admin:list")
    @GetMapping("/admin")
    public CommonResult listAdmin(Admin admin, PageQuery pageQuery) {
        return CommonResult.success(userService.getAdminList(admin, pageQuery.build()));
    }

    @ApiOperation("导入用户列表")
    @SaCheckPermission("system:admin:import")
    @Log(module = "系统管理-用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/admin/import")
    public CommonResult importAdmin(MultipartFile file) {
        return userService.importUserList(file, ADMIN);
    }

    @ApiOperation("导出用户列表")
    @SaCheckPermission("system:admin:export")
    @Log(module = "系统管理-用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/admin/export")
    public void exportAdmin(HttpServletResponse response, Admin admin) {
        ExcelUtils.exportExcel(response, "用户表", Admin.class, userService.exportAdminList(admin));
    }

    @ApiOperation("新增企业")
    @SaCheckPermission("system:enterprise:add")
    @Log(module = "系统管理-企业管理", businessType = BusinessType.INSERT)
    @PostMapping("/enterprise")
    public CommonResult addEnterprise(@Validated(AddGroup.class) @RequestBody Enterprise enterprise) {
        return userService.addOrUpdateUser(BeanUtil.toBean(enterprise, User.class), ENTERPRISE);
    }

    @ApiOperation("删除企业")
    @SaCheckPermission("system:enterprise:delete")
    @Log(module = "系统管理-企业管理", businessType = BusinessType.DELETE)
    @PostMapping("/enterprise/{ids}")
    public CommonResult deleteEnterprise(@PathVariable Integer[] ids) {
        return null;
    }

    @ApiOperation("更新企业")
    @SaCheckPermission("system:enterprise:update")
    @Log(module = "系统管理-企业管理", businessType = BusinessType.UPDATE)
    @PutMapping("/enterprise")
    public CommonResult updateEnterprise(@Validated(UpdateGroup.class) @RequestBody Enterprise enterprise) {
        return userService.addOrUpdateUser(BeanUtil.toBean(enterprise, User.class), ENTERPRISE);
    }

    @ApiOperation("查询企业详情")
    @SaCheckPermission("system:enterprise:update")
    @GetMapping("/enterprise/{id}")
    public CommonResult getEnterprise(@PathVariable Integer id) {
        return CommonResult.success(userService.getUserInfoById(id, ENTERPRISE));
    }

    @ApiOperation("查询企业列表")
    @SaCheckPermission("system:enterprise:list")
    @GetMapping("/enterprise")
    public CommonResult listEnterprise(Enterprise enterprise, PageQuery pageQuery) {
        return CommonResult.success(userService.getEnterpriseList(enterprise, pageQuery.build()));
    }

    @ApiOperation("导入企业列表")
    @SaCheckPermission("system:enterprise:import")
    @Log(module = "系统管理-企业管理", businessType = BusinessType.IMPORT)
    @PostMapping("/enterprise/import")
    public CommonResult importEnterprise(MultipartFile file) {
        return userService.importUserList(file, ENTERPRISE);
    }

    @ApiOperation("导出企业列表")
    @SaCheckPermission("system:enterprise:export")
    @Log(module = "系统管理-企业管理", businessType = BusinessType.EXPORT)
    @PostMapping("/enterprise/export")
    public void exportEnterprise(HttpServletResponse response, Enterprise enterprise) {
        ExcelUtils.exportExcel(response, "企业表", Enterprise.class, userService.exportEnterpriseList(enterprise));
    }

    @ApiOperation("新增学生")
    @SaCheckPermission("system:student:add")
    @Log(module = "系统管理-学生管理", businessType = BusinessType.INSERT)
    @PostMapping("/student")
    public CommonResult addStudent(@Validated(AddGroup.class) @RequestBody Student student) {
        return userService.addOrUpdateUser((BeanUtil.toBean(student, User.class)), STUDENT);
    }

    @ApiOperation("删除学生")
    @SaCheckPermission("system:student:delete")
    @Log(module = "系统管理-学生管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/student/{ids}")
    public CommonResult deleteStudent(@PathVariable Integer[] ids) {
        return userService.deleteUserByIds(ids);
    }

    @ApiOperation("更新学生")
    @SaCheckPermission("system:student:update")
    @Log(module = "系统管理-学生管理", businessType = BusinessType.UPDATE)
    @PutMapping("/student")
    public CommonResult updateStudent(@Validated(UpdateGroup.class) @RequestBody Student student) {
        return userService.addOrUpdateUser(BeanUtil.toBean(student, User.class), STUDENT);
    }

    @ApiOperation("查询学生详情")
    @SaCheckPermission("system:student:update")
    @GetMapping("/student/{id}")
    public CommonResult getStudent(@PathVariable Integer id) {
        return CommonResult.success(userService.getUserInfoById(id, STUDENT));
    }

    @ApiOperation("查询学生列表")
    @SaCheckPermission("system:student:list")
    @GetMapping("/student")
    public CommonResult listStudent(Student student, PageQuery pageQuery) {
        return CommonResult.success(userService.getStudentList(student, pageQuery.build()));
    }

    @ApiOperation("导入学生列表")
    @SaCheckPermission("system:student:import")
    @Log(module = "系统管理-学生管理", businessType = BusinessType.IMPORT)
    @PostMapping("/student/import")
    public CommonResult importStudent(MultipartFile file) {
        return userService.importUserList(file, STUDENT);
    }

    @ApiOperation("导出学生列表")
    @SaCheckPermission("system:student:export")
    @Log(module = "系统管理-学生管理", businessType = BusinessType.EXPORT)
    @PostMapping("/student/export")
    public void exportStudent(HttpServletResponse response, Student student) {
        ExcelUtils.exportExcel(response, "学生表", Student.class, userService.exportStudentList(student));
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public CommonResult login(@Valid @RequestBody LoginVo vo) {
        return userService.userLogin(vo);
    }

    @ApiOperation("企业注册")
    @PostMapping("/enterprise/register")
    public CommonResult register(@Validated(AddGroup.class) @RequestBody Enterprise enterprise) {
        return userService.addOrUpdateUser(BeanUtil.toBean(enterprise, User.class), ENTERPRISE);
    }

    @ApiOperation("获取当前登录用户详情")
    @GetMapping("/detail")
    public CommonResult detail() {
        UserDto userDto = SysUtils.getLoginUser();

        List<String> roleNames = roleService.getRolesByUserId(userDto.getId())
                .stream().map(Role::getName).collect(Collectors.toList());
        List<String> menuPermissions = menuService.getMenuPermissionsByUserId(userDto.getId())
                .stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());

        userDto.setRoleNames(roleNames);
        userDto.setMenuPermissions(menuPermissions);

        if (userDto.getType() != ENTERPRISE) {
            userDto.setCollegeName(collegeService.getById(userDto.getCollegeId()).getName());
            if (userDto.getType() != STUDENT) {
                userDto.setPostName(postService.getById(userDto.getPostId()).getName());
            }
        }

        StpUtil.getTokenSession().set(SysConstants.LOGIN_USER, userDto);

        return CommonResult.success(userDto);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public CommonResult logout() {
        StpUtil.logout();
        return CommonResult.success();
    }

    @ApiOperation("重置密码")
    @PutMapping("/reset/password")
    public CommonResult resetPwd(@Valid @RequestBody ResetPwdVo vo) {
        return userService.resetPwd(vo);
    }

    @ApiOperation("更新当前登录用户头像")
    @PostMapping("/avatar")
    public CommonResult updateAvatar(MultipartFile file) {
        return userService.updateUserAvatar(file);
    }

    @ApiOperation("更新当前登录用户信息")
    @PutMapping("/info")
    public CommonResult updateInfo(@RequestBody UserDto userDto) {
        userService.updateById(BeanUtil.toBean(userDto, User.class));
        StpUtil.getTokenSession().set(SysConstants.LOGIN_USER, userDto);
        return CommonResult.success();
    }

    @ApiOperation("更新密码")
    @PutMapping("/update/password")
    public CommonResult updatePwd(@Valid @RequestBody UpdatePwdVo vo) {
        return userService.updatePwd(vo);
    }

}
